package com.qf.controller;
import com.qf.service.WordService;
import com.qf.util.ExcelObject;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * author:z
 * time:2022/1/8 11:07
 * description:
 */
@RestController
@RequestMapping("/import")
public class ImportExcel {

    @Autowired
    WordService wordService;


    @RequestMapping("/export")
    public String excel(HttpServletResponse response) throws Exception {
        //临时生成测试数据
        String fileName = "导出excel例子.xls";
        String headTitle = "这是头标题";
        int colunmNum = 10;

        List<String> headTitleList = new ArrayList<String>();
        for (int i = 0; i < 10; i++) {
            headTitleList.add("第" + (i + 1) + "列标题");
        }
        List<List<String>> dataList = new ArrayList<List<String>>();
        for (int i = 0; i < 5; i++) {
            List<String> datas = new ArrayList<>();
            for (int j = 0; j < 10; j++) {
                datas.add("第" + (i + 1) + "行第" + (j + 1) + "列");
            }
            dataList.add(datas);
        }
        //1-创建一个HSSFWorkbook
        ExcelObject excel = new ExcelObject("实验数据");
        //2-写入头标题
        excel.createHeadTile(colunmNum, headTitle);//头标默认写在第一行
        //3-写入行标题
        excel.createRowTitle(headTitleList, 1);
        //4-写入具体数据
        excel.createDataByRow(2, dataList);//因为没有行标题，所以从第二行开始
        //5-生成excel文件
        excel.buildExcelFile(fileName);
        //6-浏览器下载excel
        excel.buildExcelDocument(fileName, response);

        return "导出成功！";
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @ResponseBody
    @RequestMapping("/word")
    public ResponseEntity<byte[]> ExportInterpretationSignsWord(HttpServletResponse response,
                                                                @RequestParam int id) throws Exception {

        String fileName = "导出word例子.doc";
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");

        ResponseEntity<byte[]> temp =wordService.ExportInterpretationSignsWordById(id);
        wordService.buildExcelFile(fileName);

        wordService.buildWordDocument(fileName,response);

        return temp;
    }
}
